//
//  GxOauthViewController.swift
//  microblog
//
//  Created by 记忆不为 on 16/9/22.
//  Copyright © 2016年 记忆不为. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD

class GxOauthViewController: UIViewController {
    
    override func loadView() {
        self.view = webView
        webView.navigationDelegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = GXDefaultBackgroundColor
        setupNavigation()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let request = URLRequest.init(url: url!)
        webView.load(request)
        SVProgressHUD.show(withStatus: "正在加载登录界面...")
    }
    // MARK: - 私有方法
    private func setupNavigation() ->Void{
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(fillin))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancel))
    }
    // MARK: - 事件方法
    func fillin() ->Void{
        let jsCode = "document.getElementById('userId').value='972544853@qq.com';document.getElementById('passwd').value='WO2NI100%';"
        
        // 让webView执行js代码
        webView.evaluateJavaScript(jsCode, completionHandler: nil)
    }
    func cancel() -> Void {
        SVProgressHUD.dismiss()
        self.dismiss(animated: true, completion: nil)
    }
    // MARK: - 懒加载
    private let webView : WKWebView = WKWebView()
    
}

// MARK: - wkWebView代理方法
extension GxOauthViewController: WKNavigationDelegate{
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let urlString = webView.url!.absoluteString
        if (!urlString.hasPrefix(redirect_uri)) {
            decisionHandler(.allow)
            return
        }else{
            let query = webView.url?.query
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                let nsQuery = query! as NSString
                let range = NSRange.init(location: codeString.characters.count, length: 32)
                
                let code = nsQuery.substring(with: range)
                GxUserAccountVM.shared.loadAccessToken(code: code, complete: { (error) in
                    if error != nil{
                        print("\(error)")
                        SVProgressHUD.showError(withStatus: "你的网络不给力...")
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: {
                            self.cancel()
                        })
                        return
                    }
                    self.cancel()
                    isLogin = true
                    
                })
            }else{
                cancel()
            }
            decisionHandler(.cancel)
        }
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
    }
    
}


